package com.fsts.client;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JTextArea;

/**
 * 用户发送文件时验证对方身份监听器
 * 
 * 
 * @version 1.0
 * @since JDK1.6(建议)
 */
public class ValidateIdentityListener extends Thread {

	public List<ValidateIdentityHandler> handlers = new ArrayList<ValidateIdentityHandler>();
	private JTextArea infoTextArea;
	private JButton recieveFileButton;
	private int receiveFilePort;

	public JButton getRecieveFileButton() {
		return recieveFileButton;
	}

	public void setRecieveFileButton(JButton recieveFileButton) {
		this.recieveFileButton = recieveFileButton;
	}

	public int getReceiveFilePort() {
		return receiveFilePort;
	}

	public void setReceiveFilePort(int receiveFilePort) {
		this.receiveFilePort = receiveFilePort;
	}

	public JTextArea getInfoTextArea() {
		return infoTextArea;
	}

	public void setInfoTextArea(JTextArea infoTextArea) {
		this.infoTextArea = infoTextArea;
	}

	/**
	 * Constructor
	 * 
	 * @param infoTextArea
	 * @param receiveFilePort
	 */
	public ValidateIdentityListener(JTextArea infoTextArea, int receiveFilePort,JButton recieveFileButton) {
		this.infoTextArea = infoTextArea;
		this.receiveFilePort = receiveFilePort;
		this.recieveFileButton = recieveFileButton;
	}

	@Override
	public void run() {
		this.listener();
	}

	public void listener() {
		ServerSocket ss = null;
		try {
			ValidateIdentityListener server = this;
			ss = new ServerSocket(receiveFilePort);
			Socket s = null;
			while (true) {
				s = ss.accept(); // 循环接收用户的请求
				System.out.println("获取一个连接：地址为--> " + s.getInetAddress());
				ValidateIdentityHandler h = new ValidateIdentityHandler(s,infoTextArea,recieveFileButton);
				server.handlers.add(h);
				h.setHandlers(server.handlers);
				Thread t = new Thread(h);
				t.start();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(ss != null)
					ss.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
